package com.tarena.lbs.content.service.impl;

import com.github.pagehelper.PageHelper;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.content.dao.mapper.CategoryMapper;
import com.tarena.lbs.content.pojo.param.ArticleCategoryParam;
import com.tarena.lbs.content.pojo.po.ArticleCategoryPO;
import com.tarena.lbs.content.pojo.query.ArticleCategoryQuery;
import com.tarena.lbs.content.pojo.vo.ArticleCategoryVO;
import com.tarena.lbs.content.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void addCategory(ArticleCategoryParam param) throws BusinessException {
        // 参数校验
        if (!StringUtils.hasText(param.getCategoryName())) {
            throw new BusinessException("1","分类名称不能为空");
        }
        if (param.getSort() == null) {
            throw new BusinessException("1","排序号不能为空");
        }
        if (param.getCategoryStatus() == null) {
            throw new BusinessException("1","分类状态不能为空");
        }
        // 检查名称是否已存在
        int count = categoryMapper.countByName(param.getCategoryName(), null);
        if (count > 0) {
            throw new BusinessException("1","该分类名称已存在");
        }

        // 转换为PO并保存
        ArticleCategoryPO categoryPO = new ArticleCategoryPO();
        BeanUtils.copyProperties(param, categoryPO);
        // 补充创建时间（如果数据库没有自动填充）
        categoryPO.setCreateTime(new Date());
        categoryPO.setUpdateTime(new Date());
        categoryMapper.insert(categoryPO);
    }

    @Override
    public PageResult<ArticleCategoryVO> pageList(ArticleCategoryQuery query) {
        // 分页参数校验
        if (query.getPageNo() == null || query.getPageNo() < 1) {
            query.setPageNo(1); // 默认第一页
        }
        if (query.getPageSize() == null || query.getPageSize() < 1 || query.getPageSize() > 100) {
            query.setPageSize(10); // 默认每页10条，最大100条
        }

        // 设置分页参数
        PageHelper.startPage(query.getPageNo(), query.getPageSize());

        // 查询数据
        List<ArticleCategoryPO> poList = categoryMapper.selectPage(query);
        long total = categoryMapper.selectCount(query);

        // PO转VO
        List<ArticleCategoryVO> voList = poList.stream().map(po -> {
            ArticleCategoryVO vo = new ArticleCategoryVO();
            BeanUtils.copyProperties(po, vo);
            return vo;
        }).collect(Collectors.toList());

        // 组装分页结果（修复setlist的错误）
        PageResult<ArticleCategoryVO> pageResult = new PageResult<>();
        pageResult.setObjects(voList); // 正确方法：setObjects
        pageResult.setTotal(total);
        pageResult.setPageNo(query.getPageNo());
        pageResult.setPageSize(query.getPageSize());
        return pageResult;
    }

    @Override
    public void updateStatus(Integer id, Integer categoryStatus) throws BusinessException {
        // 参数校验
        if (id == null) {
            throw new BusinessException("1", "分类ID不能为空");
        }
        if (categoryStatus == null || (categoryStatus != 0 && categoryStatus != 1)) {
            throw new BusinessException("1", "状态值必须为0（禁用）或1（启用）");
        }

        // 检查分类是否存在
        ArticleCategoryPO existPO = categoryMapper.selectById(id);
        if (existPO == null) {
            throw new BusinessException("1", "该分类不存在");
        }

        // 状态未变化则不更新
        Integer oldStatus = existPO.getCategoryStatus();
        if (oldStatus != null && oldStatus.equals(categoryStatus)) {
            return;
        }

        // 更新状态
        ArticleCategoryPO updatePO = new ArticleCategoryPO();
        updatePO.setId(id);
        updatePO.setCategoryStatus(categoryStatus);
        updatePO.setUpdateTime(new Date());
        categoryMapper.updateStatus(updatePO);
    }

    @Override
    public void deleteCategory(Integer id) throws BusinessException {
        if (id == null) {
            throw new BusinessException("1", "分类ID不能为空");
        }
        // 检查分类是否存在
        ArticleCategoryPO existPO = categoryMapper.selectById(id);
        if (existPO == null) {
            throw new BusinessException("1", "该分类不存在");
        }
        // 执行删除操作
        categoryMapper.deleteById(id);
    }
}